package com.shark.security.jwt.utils;

import java.util.concurrent.TimeUnit;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.util.CollectionUtils;

@SuppressWarnings("unchecked")
public class RedisUtil {

    private static RedisTemplate<String, Object> redisTemplate;

    public static final String Redis_Bean_Name = "redisTemplate";

    static {
        redisTemplate = SpringUtil.getBean(Redis_Bean_Name, RedisTemplate.class);
    }

    //=============================common============================

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    public static boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public static long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public static boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    public static void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    //============================String=============================

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public static <T> T get(String key) {
        return key == null ? null : (T)redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    public static boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public static boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 不存在就保存
     *
     * @param key
     * @param value
     * @param time
     * @return
     */
    public static boolean setIfAbsent(final String key, final Object value, final long time) {
        if (time <= 0) {
            return redisTemplate.opsForValue().setIfAbsent(key, value);
        } else {
            SessionCallback<Boolean> session = new SessionCallback<Boolean>() {
                @SuppressWarnings("rawtypes")
				@Override
                public Boolean execute(RedisOperations redisOperations) throws DataAccessException {
                    try {
                        redisOperations.multi();
                        redisOperations.watch(key);
                        if (redisOperations.hasKey(key)) {
                            redisOperations.discard();
                            return false;
                        }
                        redisOperations.opsForValue().set(key, value, time, TimeUnit.SECONDS);
                        redisOperations.exec();
                        return true;
                    } catch (Exception e) {
                        redisOperations.discard();
                        return false;
                    }
                }
            };
            return redisTemplate.execute(session);
        }
    }

    /**
     * 递增
     *
     * @param key 键
     * @param by  要增加几(大于0)
     * @return
     */
    public static long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     *
     * @param key 键
     * @param by  要减少几(小于0)
     * @return
     */
    public static long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }


    //============================List=============================
    /** 
     * 压栈 
     *  
     * @param key 
     * @param value 
     * @return 
     */  
    public static Long push(String key, Object value) {  
        return redisTemplate.opsForList().leftPush(key, value);  
    }
  
    /** 
     * 出栈 
     *  
     * @param key 
     * @return 
     */  
    public static <T> T pop(String key) {  
        return (T)redisTemplate.opsForList().leftPop(key);  
    }
  
    /** 
     * 入队 
     *  
     * @param key 
     * @param value 
     * @return 
     */  
    public static Long in(String key, Object value) {  
        return redisTemplate.opsForList().rightPush(key, value);  
    }
  
    /** 
     * 出队 
     *  
     * @param key 
     * @return 
     */  
    public static <T> T out(String key) {  
        return (T)redisTemplate.opsForList().leftPop(key);  
    }
  
    /** 
     * 栈/队列长 
     *  
     * @param key 
     * @return 
     */  
    public static Long length(String key) {
        return redisTemplate.opsForList().size(key);
    }
    
    /** 
     * 移除
     *  
     * @param key 
     * @param i
     * @param value
     */
    public static void remove(String key, long i, Object value) {
    	redisTemplate.opsForList().remove(key, i, value);
    }
}
